//
//  LocationService.swift
//  定位功能类
//
//  Created by 千策万划-mini on 2025/4/30.
//

import CoreLocation
import Foundation

class LocationService: NSObject, CLLocationManagerDelegate {

    // MARK: - Properties
    private var locationManager: CLLocationManager
    private var currentLocation: CLLocationCoordinate2D = .init()
    private var need: Bool = false
    private var doup: (() -> Void)?
    private var isFirstUpdate: Bool = true

    // MARK: - Singleton
    static let shared = LocationService()

    // MARK: - Initialization
    override private init() {
        locationManager = CLLocationManager()
        super.init()

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 10 // 每10米更新一次, 可根据需求调整

        // 检查授权状态
        checkAuthorizationStatus()
    }

    // MARK: - Public Methods
    func startUpdatingLocation() {
        locationManager.startUpdatingLocation()
    }

    func startUploca(doup: @escaping () -> Void) {
        locationManager.startUpdatingLocation()
        need = true
        self.doup = doup
        isFirstUpdate = true // 重置标记

        DispatchQueue.main.asyncAfter(deadline: .now() + 6) { [weak self] in
            guard let self = self else { return }
            if self.need {
                self.need = false
                doup()
            }
        }
    }

    func getCurrentLocation() -> CLLocationCoordinate2D {
        return currentLocation
    }

    // MARK: - Private Methods
    private func checkAuthorizationStatus() {
        let status = locationManager.authorizationStatus
        switch status {
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
        case .authorizedWhenInUse, .authorizedAlways:
            startUpdatingLocation()
        default:
            break
        }
    }

    // MARK: - CLLocationManagerDelegate
    func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let newLocation = locations.last else { return }
        currentLocation = newLocation.coordinate

        // 只在第一次更新或需要更新时执行回调
        if let doup = doup, need {
            if isFirstUpdate {
                isFirstUpdate = false
                need = false
                doup()
            }
        }
    }

    func locationManager(_: CLLocationManager, didFailWithError error: Error) {
        print("Location update failed: \(error.localizedDescription)")
    }

    func locationManagerDidChangeAuthorization(_: CLLocationManager) {
        checkAuthorizationStatus()
    }

    // 添加应用进入后台的处理
    func applicationDidEnterBackground() {
        locationManager.stopUpdatingLocation()
    }

    // 添加应用进入前台的处理
    func applicationWillEnterForeground() {
        if need {
            locationManager.startUpdatingLocation()
        }
    }
}
